package com.tangji.signaltower.runners.client;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created with IntelliJ IDEA.
 * User: Amarendar
 * Date: 2020/6/17
 * Time: 下午6:06
 */
public class ForexPoHeartBeatClientHandler extends ChannelInboundHandlerAdapter {

    private static final Logger log = LoggerFactory.getLogger(ForexPoHeartBeatClientHandler.class);

    /**
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                if (ForexPoNettyClient.getInst().getHandshaker() == null
                        || !ForexPoNettyClient.getInst().getHandshaker().isHandshakeComplete()) {
                    log.info("ForexPoHeartBeatClientHandler,握手未成功,不做处理");
                } else {
                    log.info("ForexPoHeartBeatClientHandler,服务端通讯异常,尝试重连");
                    ctx.channel().close();
                }
            } else if (event.state() == IdleState.WRITER_IDLE) {
                JSONObject initData = new JSONObject();
                initData.put("type", "pong");
                String s = initData.toJSONString();
                log.info("ForexPoHeartBeatClientHandler,发送心跳,{}", s);
                ctx.channel().writeAndFlush(new TextWebSocketFrame(s));
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
